package com.web.handler;

import com.web.dao.SysMenuMapper;
import com.web.entity.SysMenu;
import com.web.entity.SysMenuExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 * @author xukk
 * @date 2017/6/5
 */
@Slf4j
@Service
public class SecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    public static void clearCache(){
        resourceMap=null;
    }
    /**
     * ApplicationContext ctx =  WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
     * CustomInvocationSecurityMetadataSource cs=(CustomInvocationSecurityMetadataSource)ctx.getBean("customSecurityMetadataSource",com.zst.meadow.security.CustomInvocationSecurityMetadataSource.class);
     * cs.loadResourceDefine();
     * 加载所有角色与权限的关系
     */
    private void loadAllResources() {
        if (resourceMap == null) {
            resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
            List<SysMenu> sysMenuList=sysMenuMapper.selectByExample(new SysMenuExample());
            if(sysMenuList!=null){
                for (SysMenu sysMenu : sysMenuList) {
                    if(sysMenu.getEnabled()&&sysMenu.getUrl()!=null){
                        Collection<ConfigAttribute> configAttributes = resourceMap.get("ROLE_menu:"+sysMenu.getUrl());
                        if (configAttributes == null) {
                            configAttributes = new ArrayList<ConfigAttribute>();
                        }
                        ConfigAttribute configAttribute = new SecurityConfig("ROLE_menu:"+sysMenu.getUrl());
                        configAttributes.add(configAttribute);
                        resourceMap.put(sysMenu.getUrl(), configAttributes);

                    }
                }
            }

        }
    }

    /**
     * 返回所请求资源所需要的权限,根据roleName得到模块
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        if (resourceMap == null) {
            loadAllResources();
        }
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        AntPathRequestMatcher matcher;
        String resUrl;
        if(resourceMap!=null) {
            for (Iterator<String> iter = resourceMap.keySet().iterator(); iter.hasNext(); ) {
                resUrl = iter.next();
                String resUrl1 = resUrl;
                if (!resUrl1.startsWith("/")) {
                    resUrl1 = "/" + resUrl;
                }
                matcher = new AntPathRequestMatcher(resUrl1);
                if (matcher.matches(request)) {
                    return resourceMap.get(resUrl);
                }
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
